import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Thread_ThreadPoolExecutor {

	public static void main(String[] args) throws InterruptedException {
		BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(200);
		ThreadFactory tf = Executors.defaultThreadFactory();
		ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 40, 20, TimeUnit.MINUTES, queue, tf);
		// 三种添加线程方法，add为抛异常，offer返回boolean值，put直到添加成功为止。
		// 三种移线程方法 remove为抛异常，poll为返回boolean值，take等待直到有线程可以被移除
		Thread thread = null;
		for (int i = 0; i < 100; i++) {
			thread = initThread(i);
			// queue.add(thread);// add为抛异常
			// queue.put(initThread(i));// put直到添加成功为止
			// boolean rst = queue.offer(thread);// offer返回boolean值
			boolean rst = false;
			while (!rst) {
				rst = add(executor, thread);
				if (!rst)
					Thread.sleep(100);
			}
			System.out.println(executor.getActiveCount());
		}
		System.out.println("over!!" + queue.size());
		executor.shutdown();
	}

	public static boolean add(ThreadPoolExecutor executor, Thread thread) {
		try {
			executor.execute(thread);
			return true;
		} catch (RejectedExecutionException e) {
			return false;
		}

	}

	public static Thread initThread(final long id) {
		return new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println(Thread.currentThread().getName());
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "TestThread." + id);
	}

}
